#include "graphletsmanager.h"
#include <QApplication>
#include <QDir>
#include "graphletsutil.h"
/**
 * 管理逻辑，所有图元采用本地存储，所有图元存储在根目录
 * 的graphlets目录下，所有图元，采用文件独立存储，考虑
 * 到知识产权，所有图元将加密存储，图元后缀名为gsvg
 * 由于SVG的矢量性，图元的小图标均采用SVG渲染。
 * @brief GraphletsManager::GraphletsManager
 */

#ifdef _MSC_VER  // vc
#pragma data_seg("MyShared")
void *g_pRtdbObj = NULL;
#pragma data_seg()
#pragma comment(linker, "/SECTION:MyShared,RWS")
#else // gcc
void *g_pGraphletsManagerObj __attribute__ ((section("MyShared"))) = NULL;
#endif

QMutex GraphletsManager::m_mutex;

GraphletsManager::GraphletsManager() {
    QString rootPath = QApplication::applicationDirPath();
    rootPath.append("/graphlets");
    qDebug() << "GraphletsManager::GraphletsManager:" << rootPath;
    loadGraphlets(rootPath);
}

GraphletsManager *GraphletsManager::instance()
{
    QMutexLocker locker(&m_mutex);
    if(g_pGraphletsManagerObj == NULL) {
        g_pGraphletsManagerObj = new GraphletsManager();
    }
    return (GraphletsManager *)g_pGraphletsManagerObj;
}

void GraphletsManager::loadGraphlets(QString graphFileUrl){
    QDir graphDir(graphFileUrl);
    QStringList sfiles = graphDir.entryList(QStringList() << "*.gsvg");
    qDebug() << "GraphletsManager::loadGraphlets:file size->" << sfiles.size();
    foreach(QString fileName,sfiles){
        qDebug() << "GraphletsManager::loadGraphlets:process file->" << fileName;
        QString fileAbsolutePath = graphFileUrl;
        fileAbsolutePath.append("/");
        fileAbsolutePath.append(fileName);

        QString fileXml = loadGraphletsXml(fileAbsolutePath);
        //fileXml = GraphletsUtil::decodeSvgCode(fileXml);
        Graphlets tGraph = GraphletsUtil::loadFromXml(fileXml);
        //处理缩略图标
        QString thumbAbsolutePath = graphFileUrl;
        thumbAbsolutePath.append("/");
        thumbAbsolutePath.append(fileName);
        thumbAbsolutePath.append(".png");
        qDebug() << "GraphletsManager::loadGraphlets:gen thumbnail->" << thumbAbsolutePath;
        QString tempXml = fileXml;
        for(int i=0;i<tGraph.m_gVars.size();i++){
            GraphletsVar var = tGraph.m_gVars.at(i);
            tempXml = tempXml.replace("var("+var.m_id+")",var.m_initialValue);
        }
        GraphletsUtil::genThumbnail(tempXml,thumbAbsolutePath);
        tGraph.m_gIcon = thumbAbsolutePath;
        //添加到列表清单
        m_gList.append(tGraph);
    }

}

QString GraphletsManager::loadGraphletsXml(QString fileName){
    QString res;
    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        res = in.readAll();
        file.close();
    }
    qDebug() << "GraphletsManager::loadGraphletsXml3->" << res.toUtf8();
    return res.toUtf8();
}


QList<Graphlets> GraphletsManager::getGraphletsList(){
    return m_gList;
}
